package com.neo.shiro.filters;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSONObject;

/**
 * ajax shiro session超时统一处理
 * 
 * 参考：http://looooj.github.io/blog/2014/06/17/shiro-user-filter.html
 * @author L.cm
 *
 */

public class ShiroAjaxFilter extends AccessControlFilter {

	private Logger logger = LoggerFactory.getLogger(ShiroAjaxFilter.class);
	
	private String unauthorizedUrl = "unauthorized.html";
	//private String loginUrl = "/login";
	
	public ShiroAjaxFilter() {
		super();
		logger.info("ShiroAjaxSessionFilter init");
	}

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
		logger.info("==>isAccessAllowed()");
		String[] roles = (String[])mappedValue;
        if(roles == null) {
            return true;//如果没有设置角色参数，默认成功
        }
        for(String role : roles) {
            if(getSubject(request, response).hasRole(role)) {
                return true;
            }
        }
		return false;
	}
	
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		logger.info("==>onAccessDenied()");
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String xmlHttpRequest = httpServletRequest.getHeader("X-Requested-With");
        if (!StringUtils.isEmpty(xmlHttpRequest) && xmlHttpRequest.equalsIgnoreCase("XMLHttpRequest")) {//如果是ajax返回指定格式数据
            logger.info("==>Ajax Access Denied");
            Map<String,String> resultMap = new HashMap<String, String>();
			logger.info("==>当前用户没有权限，并且是Ajax请求！");
			resultMap.put("code", "400");
			resultMap.put("message", "\u5F53\u524D\u7528\u6237\u6CA1\u6709\u767B\u5F55\uFF01");
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json; charset=utf-8");
            PrintWriter out = httpServletResponse.getWriter();
            out.write(JSONObject.toJSONString(resultMap));
            if (StringUtils.hasText(unauthorizedUrl)) {//如果有未授权页面跳转过去
                WebUtils.issueRedirect(request, response, unauthorizedUrl);
            } else {//否则返回401未授权状态码
                WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }
        } else {//如果是普通请求进行重定向
            httpServletResponse.sendRedirect("/403");
        }
		return false;
	}
}